<?php
/**
 * 缓存工具
 */

namespace common\utils;

use common\models\Banner;
use common\models\BannerItem;
use common\models\Catalog;
use common\models\Config;
use common\models\Links;
use common\models\Module;
use common\models\Post;
use common\models\PostAttr;

class XCache
{
    /* @var $cache \yii\caching\Memcache */
    //private static $cache;
    const CACHE_CONFIG = "_config";
    const CACHE_BANNER = "_banner";
    const CACHE_CATALOG = "_catalog";
    const CACHE_CATALOG_NAV = "_catalogNav";
    const CACHE_LINKS = "_links";
    const CACHE_MODULES = "_modules";
    const CACHE_POST = "_post";
    const CACHE_POST_ITEMS = "_postItems";
    const CACHE_POST_PREV = "_postPrev";
    const CACHE_POST_NEXT = "_postNext";

    /**
     * 获取配置
     * @return array|mixed|\yii\db\ActiveRecord[]
     */
    public static function config()
    {
        $configs = self::get(self::CACHE_CONFIG);
        if ($configs)
            return $configs;
        $conf = [];
        $configs = Config::find()->all();
        foreach ((array)$configs as $config) {
            $conf[$config['variable']] = $config['value'];
        }
        self::set(self::CACHE_CONFIG, $conf);
        return $conf;
    }

    /**
     * 删除配置
     */
    public static function configDelete()
    {
        self::delete(self::CACHE_CONFIG);
    }

    /**
     * 获取自定义模块
     * @return array|mixed|\yii\db\ActiveRecord[]
     */
    public static function modules()
    {
        $modules = self::get(self::CACHE_MODULES);
        if ($modules)
            return $modules;
        $modules = Module::find()->all();
        $mdu = [];
        foreach ((array)$modules as $module) {
            $mdu[$module['name']] = $module['content'];
        }
        self::set(self::CACHE_MODULES, $mdu);
        return $mdu;
    }

    /**
     * 删除自定义模块
     */
    public static function moduleDelete()
    {
        self::delete(self::CACHE_MODULES);
    }

    /**
     * 获取幻灯片
     * @param string $name 幻灯片名称
     * @return array|mixed|\yii\db\ActiveRecord[]
     */
    public static function banner($name)
    {
        $banners = self::get(self::CACHE_BANNER . $name);
        if ($banners)
            return $banners;
        $items = [];
        $model = Banner::findOne(['name' => $name]);
        if ($model) {
            $items = BannerItem::find()->select("src,title,url")->where("banner_id=$model->id")->orderBy("sort asc")->asArray()->all();
        }
        self::set(self::CACHE_BANNER . $name, $items);
        return $items;
    }

    /**
     * 删除幻灯片
     */
    public static function bannerDelete($name)
    {
        self::delete(self::CACHE_BANNER . $name);
    }

    /***
     * 获取前台主导航
     * @param int $depth 深度，目前只支持1和2，默认为1
     * @return array|mixed|\yii\db\ActiveRecord[]
     */
    public static function catalogNav($depth = 1)
    {
        $navigation = self::get(self::CACHE_CATALOG_NAV . $depth);
        if ($navigation)
            return $navigation;
        $list = [];
        if ($depth == 1) {
            $list = Catalog::find()->select('alias,name,us_name')->where("parent_id=0 and frontend_nav=1")->orderBy("sort ASC, id ASC")->asArray()->all();
        } elseif ($depth == 2) {
            $data = Catalog::find()->select('id,parent_id,alias,name,us_name')->where('frontend_nav=1')->orderBy("sort ASC, id ASC")->asArray()->all();
            $n = 0;
            foreach ((array)$data as $item) {
                if ($item['parent_id'] === '0') {
                    $list[$n] = ['alias' => $item['alias'], 'name' => $item['name'],'us_name'=>$item['us_name']];
                    foreach ((array)$data as $value) {
                        if ($item['id'] == $value['parent_id']) {
                            $list[$n]['childItems'][] = ['alias' => $value['alias'], 'name' => $value['name'],'us_name'=>$item['us_name']];
                        }
                    }
                    $n++;
                }
            }
        }
        self::set(self::CACHE_CATALOG_NAV . $depth, $list);
        return $list;
    }
    /***
     * 获取前台主导航
     */
    public static function catalogAliasNav($alias)
    {
        $navigation = self::get(self::CACHE_CATALOG_NAV . $alias);
        if ($navigation)
            return $navigation;
            $data = Catalog::find()->select('id,parent_id,alias,name,us_name')->where("`alias`='$alias'")->orderBy("sort ASC, id ASC")->asArray()->one();
            if($data){
                $pid=$data['id'];
                $childs = Catalog::find()->select('id,parent_id,alias,name,us_name')->where('parent_id='.$pid)->orderBy("sort ASC, id ASC")->asArray()->all();
                $data['childItems']=$childs;
            }
            $list=$data;
        self::set(self::CACHE_CATALOG_NAV . $alias, $list);
        return $list;
    }
    /**
     * 删除前台主导航
     */
    public static function catalogNavDelete()
    {
        self::delete(self::CACHE_CATALOG_NAV . '1');
        self::delete(self::CACHE_CATALOG_NAV . '2');
    }

    /**
     * 获取内容项
     * @param $alias
     * @param int $number
     * @param int $recommend
     * @return array|mixed|\yii\db\ActiveRecord[]
     */
    public static function postItems($alias, $number = 6, $recommend = 0)
    {
        $items = self::get(self::CACHE_POST_ITEMS . $alias . $number . '_' . $recommend);
        if ($items)
            return $items;
        $data = Post::find()->with('attr')->select("id,title,author,intro,face");
        //获取$catalogId子类
        $catalog = Catalog::findOne(['alias' => $alias]);
        if (!$catalog) {
            return [];
        }
        $childIdes = $catalog->getChildIdes($catalog->id);
        if ($childIdes) {
            $ids = $catalog->id . ',' . $childIdes;
            $data->where("catalog_id in($ids)");
        } else {
            $data->where("catalog_id=$catalog->id");
        }
        if ($recommend) {
            $data->andWhere("recommend=1");
        }
        $list = $data->orderBy("recommend desc,sort asc,id desc")->limit($number)->asArray()->all();
        foreach ((array)$list as $key => $item) {
            $list[$key]['url'] = \yii\helpers\Url::to(['/post', 'id' => $item['id']]);
            //补充内容属性
            //$attres = PostAttr::find()->where("post_id=" . $item['id'])->asArray()->all();
            $attributes = [];
            foreach ((array)$item['attr'] as $attr) {
                $attributes[$attr['name']] = $attr['val'];
            }
            $list[$key]['attributes'] = $attributes;
        }

        self::set(self::CACHE_POST_ITEMS . $alias . $number . '_' . $recommend, $list);
        return $list;
    }

    /***
     * 获取友情链接
     * @param $type
     * @return array|mixed|\yii\db\ActiveRecord[]
     */
    public static function links($type)
    {
        $items = self::get(self::CACHE_LINKS . $type);
        if ($items)
            return $items;
        $list = Links::find()
            ->select('name,url,attach')
            ->where("status=1 and type=:type", [":type" => $type])
            ->orderBy("sort asc,id asc")
            ->asArray()
            ->all();
        if ($type == '图片') {
            foreach ($list as $key => $item) {
                if ($item['attach']) {
                    $list[$key]['attach'] = \Yii::getAlias('@frontendUrl') . $item['attach'];
                }
            }
        }
        self::set(self::CACHE_LINKS . $type, $list);
        return $list;
    }

    /**
     * 删除友情链接
     */
    public static function linksDelete($type)
    {
        self::delete(self::CACHE_LINKS . $type);
    }

    /**
     * 获取栏目
     * @param string $alias
     * @return mixed|static
     */
    public static function catalog($alias)
    {
        $model = self::get(self::CACHE_CATALOG . $alias);
        if ($model)
            return $model;
        $model = Catalog::findOne(['alias' => $alias]);
        self::set(self::CACHE_CATALOG . $alias, $model);
        return $model;
    }

    /**
     * 删除栏目
     */
    public static function catalogDelete($alias)
    {
        self::delete(self::CACHE_CATALOG . $alias);
    }

    /**
     * 获取栏目
     * @param int $id
     * @return \common\models\Catalog
     */
    public static function catalogById($id)
    {
        $model = self::get(self::CACHE_CATALOG . $id);
        if ($model)
            return $model;
        $model = Catalog::findOne($id);
        self::set(self::CACHE_CATALOG . $id, $model);
        return $model;
    }

    /**
     * 删除栏目
     */
    public static function catalogDeleteById($id)
    {
        self::delete(self::CACHE_CATALOG . $id);
    }

    /**
     * 获取内容
     * @param $id
     * @return \common\models\Post
     */
    public static function post($id)
    {
        $model = self::get(self::CACHE_POST . $id);
        if ($model)
            return $model;
        $model = Post::findOne($id);
        self::set(self::CACHE_POST . $id, $model);
        return $model;
    }

    /**
     * 删除内容
     */
    public static function postDelete($id)
    {
        self::delete(self::CACHE_POST . $id);
    }

    /**
     * 设置缓存
     * @param string $key
     * @param mixed $value
     * @param int $duration 过期时间，单位为秒
     * @return bool
     */
    public static function set($key, $value, $duration = 0)
    {
        //self::$cache = \Yii::$app->mCache;
        return \Yii::$app->mCache->set($key, $value, $duration);
    }

    /***
     * 获取缓存
     * @param string $key
     * @return mixed
     */
    public static function get($key)
    {
        return \Yii::$app->mCache->get($key);
    }

    /**
     * 删除缓存
     * @param string $key
     * @return bool
     */
    public static function delete($key)
    {
        return \Yii::$app->mCache->delete($key);
    }

    /**
     * 删除缓存中的所有数据
     * @return bool
     */
    public static function flush()
    {
        return \Yii::$app->mCache->flush();
    }
}